﻿using Client;
using Shared.Method;
using Shared.Model;
using StationClient.Dialog;
//using StationClient.HelpClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StationClient
{
    public partial class FormStation : Form
    {
        private STATION _station = null;

        private FormBox _box = null;
        private FormTest _test = null;
        //private FormCheck _check = null;
        private FormLabelCheck _check = null;
        private FormBackGround _backGround = null;

        private string _serverNetwork = "10.0.0";

        public FormStation()
        {
            InitializeComponent();
        }
        //保存信息到内存
        private void SetTextBox()
        {
            if (_station == null) return;

            //保存姓名和描述
            if (this.InvokeRequired)
            {
                Action d = new Action(SetTextBox);
                Invoke(d);
            }
            else
            {



                string name = this.textBoxStaName.Text.Trim();
                string context = this.textBoxStaContext.Text.Trim();
                string flag = this.comboBoxStaFlag.Text.Trim();
                if (!string.IsNullOrEmpty(name))
                    _station.NAME = name;
                if (!string.IsNullOrEmpty(context))
                    _station.CONTEXT = context;
                if (!string.IsNullOrEmpty(flag))
                    _station.FLAG = flag;

                try
                {
                    this.textBoxStaId.Text = _station.ID.ToString();
                    this.textBoxStaName.Text = _station.NAME;

                    //设置默认的工号的名称
                    _station.WORKER_NAME = string.IsNullOrEmpty(_station.WORKER_NAME) ? "友创达" : _station.WORKER_NAME;
                    _station.WORKER_ID = (_station.WORKER_ID == null) ? 88888888 : _station.WORKER_ID;

                    this.textBoxWorkerName.Text = _station.WORKER_NAME;
                    this.textBoxLineId.Text = _station.LINE_ID.ToString();
                    this.textBoxFlowId.Text = _station.FLOW_ID.ToString();
                    this.textBoxNodeId.Text = _station.NODE_ID.ToString();
                    this.textBoxWorkerId.Text = _station.WORKER_ID.ToString();
                    this.textBoxStaContext.Text = _station.CONTEXT;
                    this.comboBoxStaFlag.Text = _station.FLAG;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        //加载工位信息
        private void FormStation_Load(object sender, EventArgs e)
        {
            try
            {
                //加载软件版本
                string version = Application.ProductVersion.ToString();

                this.Text = "友创达客户端 V"+version;

                //服务器网段           
                string server = AppSetting.GetValue("ServerNetwork");
                if (!string.IsNullOrEmpty(server))
                {
                    _serverNetwork = server;
                }

                //将三个工具的按钮设置为不可用状态
                this.buttonBox.Enabled = false;
                this.buttonStart.Enabled = false;
                //this.buttonMessageCheck.Enabled = false;

                //获得当前电脑的MAC地址
                string macAddress = MacClass.GetLocalMac(_serverNetwork);

                //如果MAC地址为空的话，给出提示信息
                if (string.IsNullOrEmpty(macAddress))
                {
                    MessageBox.Show("未能获得MAC地址，请检查");
                    return;
                }

                //通过MAC地址获得当前的工位信息
                var staW = new STATION();
                staW.SetWhere();
                staW.MAC = macAddress;
                var staRes = MethodWcf.SelectStationClient(staW);
                if(staRes.result)
                {
                    _station = staRes.value[0];
                }

                //System.Threading.Thread.Sleep(2000);

                this.textBoxStaMAC.Text = macAddress;

                if (_station!=null)//如果查到了工位信息
                {
                    //_station = staRes.value[0];

                    SetTextBox();//设置内容

                    this.textBoxStaName.Enabled = false;
                    this.textBoxLineId.Enabled = false;
                    this.textBoxNodeId.Enabled = false;

                    this.textBoxStaContext.Enabled = false;
                    this.buttonSave.Enabled = false;
                    this.comboBoxStaFlag.Enabled = false;

                    if (_station.FLAG == "测试工位")
                    {
                        this.buttonStart.Enabled = true;
                    }
                    else if (_station.FLAG == "装箱工位")
                    {
                        //this.buttonWriteSn.Enabled = true;
                        this.buttonBox.Enabled = true;
                    }
                    else if (_station.FLAG == "信息检查")
                    {
                        this.buttonMessageCheck.Enabled = true;
                    }
                }
                else//没有查到工位信息
                {
                    this.buttonChange.Enabled = false;

                    _station = new STATION
                    {
                        MAC = macAddress
                    };
                }


                GetStationMsg(macAddress);//每过20S获取一次站位信息
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetStationMsg(string staMac)
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    System.Threading.Thread.Sleep(15000);

                    var staW = new STATION();
                    staW.SetWhere();
                    staW.MAC = staMac;
                    var staRes = MethodWcf.SelectStationClient(staW);

                    if (staRes.result
                    && (staRes.value[0].NODE_ID != _station.NODE_ID || staRes.value[0].LINE_ID != _station.LINE_ID))
                    {
                        //_station = staRes.value[0];
                        //SetTextBox();//设置内容
                        Application.Exit();
                    }

                }

            });
        }

        /// <summary>
        /// 判断此人是否在其他工位上，给出提示信息，并让其选择
        /// </summary>
        /// <returns></returns>
        private bool CheckStationAndContinue()
        {
            _station.Clear();
            _station.SetWhere();
            _station.WORKER_ID = _station.WORKER_ID;

            var staRes = MethodWcf.SelectStationClient(_station);
            if (!staRes.result) return true;//如果在工位表中没有相关的信息，则不做任何处理
            if (staRes.value.Count == 1 && staRes.value[0].ID == _station.ID) return true;//如果查询到的员工工位ID和当前保存的ID一样也不做处理

            //给出警告信息
            var check = MessageBox.Show("此员工在其他工位上，是否调换工位？选择是将清除原来工位上的相关信息！", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (check == DialogResult.Yes)
            {
                //清空之前工位上员工的信息
                for (int i = 0; i < staRes.value.Count; i++)
                {
                    STATION sta = staRes.value[0];
                    sta.Clear();
                    sta.SetWhere();
                    sta.ID = sta.ID;

                    sta.SetUpdate();
                    sta.WORKER_ID = null;
                    sta.WORKER_NAME = null;

                    var res = MethodWcf.UpdateStationClient(sta);
                    if (!res.result)//更新失败，弹出消息框
                    {
                        MessageBox.Show(res.message);
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        //修改工位信息
        private void buttonChange_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckStationAndContinue() == false) return;//如果查到了员工在其他工位上选择不更新，则不改变目前的状况

                _station.Clear();
                _station.SetWhere();//设置条件
                _station.ID = _station.ID;
                _station.SetUpdate();//设置更新内容，更新员工信息
                _station.WORKER_ID = _station.WORKER_ID;
                _station.WORKER_NAME = _station.WORKER_NAME;

                var res = MethodWcf.UpdateStationClient(_station);
                if (res.result)
                {
                    MessageBox.Show("修改成功");
                }
                else
                {
                    MessageBox.Show(res.message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //保存工位信息
        private void buttonSave_Click(object sender, EventArgs e)
        {
            SetTextBox();//将工位信息检查内存中

            if (string.IsNullOrEmpty(_station.NAME))
            {
                MessageBox.Show("请输入工位名称");
                return;
            }

            if (string.IsNullOrEmpty(_station.MAC))
            {
                MessageBox.Show("未能获得MAC地址，请检查网络是否连接");
                return;
            }

            try
            {
                if (CheckStationAndContinue() == false) return;//如果查到了员工在其他工位上选择不更新，则不改变目前的状况
                //写需要保存的信息
                _station.SetUpdate();
                _station.MAC = _station.MAC;
                _station.NAME = _station.NAME;
                _station.LINE_ID = _station.LINE_ID;
                _station.FLOW_ID = _station.FLOW_ID;
                _station.NODE_ID = _station.NODE_ID;
                _station.WORKER_ID = _station.WORKER_ID;
                _station.WORKER_NAME = _station.WORKER_NAME;
                _station.CONTEXT = _station.CONTEXT;
                _station.FLAG = _station.FLAG;

                var res = MethodWcf.InsertStationClient(_station);
                _station.Clear();//清空

                if (res.result)
                {
                    SetTextBox();
                    MessageBox.Show("保存成功");

                    //固定所有的选项，只保留修改工序的权利
                    this.textBoxStaName.Enabled = false;
                    this.textBoxLineId.Enabled = false;
                    this.textBoxNodeId.Enabled = false;

                    this.textBoxStaContext.Enabled = false;
                    this.buttonSave.Enabled = false;
                    this.buttonChange.Enabled = true;

                    this.FormStation_Load(sender, e);
                }
                else
                {
                    MessageBox.Show(res.message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //选择产线
        private void textBoxLineId_Enter(object sender, EventArgs e)
        {
            DialogLine lineTable = new DialogLine(_station);
            lineTable.ShowDialog();
            SetTextBox();
        }

        //选择工序
        private void textBoxNodeId_Enter(object sender, EventArgs e)
        {
            //这里处理获得工序ID的事情
            //判断产线ID和流程ID是否存在，如果不存在，则给出提示信息不存在

            if (_station.LINE_ID == null || _station.FLOW_ID == null || _station.FLOW_ID == 0)
            {
                MessageBox.Show("请先选择产线后再操作");
                return;
            }

            NODE nodeWhere = new NODE();
            nodeWhere.SetWhere();
            nodeWhere.FLOW_ID = _station.FLOW_ID;

            DialogNode nodeSelect = new DialogNode(nodeWhere, _station);
            nodeSelect.ShowDialog();
            SetTextBox();
        }

        //选择员工
        private void textBoxWorkerId_Enter(object sender, EventArgs e)
        {
            DialogWorker workerSelect = new DialogWorker(_station);
            workerSelect.ShowDialog();
            SetTextBox();
        }

        //选择产线
        private void textBoxLineId_MouseClick(object sender, MouseEventArgs e)
        {
            this.textBoxLineId_Enter(null, null);
        }

        //打开工序窗口
        private void textBoxNodeId_MouseClick(object sender, MouseEventArgs e)
        {
            this.textBoxNodeId_Enter(null, null);
        }

        //打开员工信息窗口
        private void textBoxWorkerId_MouseClick(object sender, MouseEventArgs e)
        {
            this.textBoxWorkerId_Enter(null, null);
        }

        //测试
        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (_station == null || _station.NODE_ID == null || _station.WORKER_ID == null)
            {
                MessageBox.Show("不能测试，请确定此工位信息配置完整");
                return;
            }

            _test = new FormTest(this,_station);
            _test.Show();
            this.Close();
        }

        //装箱
        private void buttonBox_Click(object sender, EventArgs e)
        {
            //判断能否开始测试
            if (_station == null || _station.NODE_ID == null || _station.WORKER_ID == null)
            {
                MessageBox.Show("不能测试，请确定此工位信息配置完整");
                return;
            }
            _box = new FormBox(this, _station);
            _box.Show();
            this.Close();
        }

        //包装检查
        private void buttonMessageCheck_Click(object sender, EventArgs e)
        {
            //判断能否开始测试
            if (_station == null || _station.NODE_ID == null || _station.WORKER_ID == null)
            {
                MessageBox.Show("不能测试，请确定此工位信息配置完整");
                return;
            }
            _check = new FormLabelCheck(this, _station);
            _check.Show();
            this.Close();
        }

        //测试后台
        private void buttonBackGround_Click(object sender, EventArgs e)
        {
            //判断能否开始测试
            if (_station == null || _station.NODE_ID == null || _station.WORKER_ID == null)
            {
                MessageBox.Show("不能测试，请确定此工位信息配置完整");
                return;
            }

            //让其他的按钮失效
            //this.buttonMessageCheck.Enabled = false;
            this.buttonBox.Enabled = false;
            this.buttonStart.Enabled = false;
            this.buttonTestBackGround.Enabled = false;

            _backGround = new FormBackGround(this, _station);
            _backGround.Show();
            this.Close();
        }

        //关闭窗体到最小化状态
        private void FormStation_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗体关闭原因为单击"关闭"按钮或Alt+F4  
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;           //取消关闭操作 表现为不关闭窗体  
                this.Hide();               //隐藏窗体  
            }
        }

        //显示窗体
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //显示
            this.Show();   //窗体显示  
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小  
            this.Activate();   //激活窗体给予焦点  
        }

        //隐藏窗体
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //隐藏
            this.Hide();    //隐藏窗体  
        }

        //退出软件
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            //退出
            if (MessageBox.Show("确定要退出程序?", "安全提示",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Warning)    == DialogResult.Yes)
            {
                _box?.Close();//关闭盒装窗口
                _test?.Close();//关闭测试窗口
                //_check?.Close();//关闭信息检查窗口

                this.notifyIconSmallest.Visible = false;   //设置图标不可见  
                this.Close();                  //关闭窗体  
                this.Dispose();                //释放资源  
                Application.Exit();            //关闭应用程序窗体  
            }
        }

        //双击右下角图标，打开客户端窗口
        private void NotifyIconSmallest_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //显示
            this.Show();    //窗体显示  
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小  
            this.Activate();    //激活窗体给予焦点  
        }

        private void buttonLabelCheck_Click(object sender, EventArgs e)
        {
            //判断能否开始测试
            if (_station == null || _station.NODE_ID == null || _station.WORKER_ID == null)
            {
                MessageBox.Show("不能测试，请确定此工位信息配置完整");
                return;
            }

            var label = new FormLabelCheck(this, _station);
            label.Show();
            this.Close();
        }
    }
}
